package dgwcode.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import dgwcode.domain.Employee;
import utils.HibernateUtils;

public class HibernateTest2 {

	private Session session;

	@Before
	public void init() {
		session = HibernateUtils.getSession();
		session.beginTransaction();
	}
	
	/**
	 * 离线查询
	 */
	@Test
	public void testLiXianQBC() {
		//service 层 封装与 session 无关的 criteria
		DetachedCriteria detachedCriteria  = DetachedCriteria.forClass(Employee.class);
		detachedCriteria .add(Restrictions.eq("id", 1));
		// dao 层
		Criteria criteria = detachedCriteria .getExecutableCriteria(session);
		List<Employee> list = criteria.list();
		for (Employee obj  : list) {
			System.out.println(obj);
		}
	}
	

	/**
	 * 条件查询
	 */
	@Test
	public void testCiucustionQBC() {
		Criteria criteria = session.createCriteria(Employee.class);
		
		//按照名称查询
		//criteria.add(Restrictions.eq("name", "A-11"));
		//模糊查询
		//criteria.add(Restrictions.like("name", "%A%"));
		//条件并列查询
		criteria.add(Restrictions.eq("name", "A-11"));
		criteria.add(Restrictions.eq("email", "A+11@qq.com"));

		List<Employee> list = criteria.list();
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}

	// 排序
	@Test
	public void testOrderByQBC() {
		Criteria criteria = session.createCriteria(Employee.class);

		criteria.addOrder(Order.desc("id"));

		List<Employee> list = criteria.list();
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}

	// 分页查询
	@Test
	public void testPageQBC() {
		Criteria criteria = session.createCriteria(Employee.class);

		criteria.setFirstResult(1);
		criteria.setMaxResults(10);

		List<Employee> list = criteria.list();
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}

	// 查询全部
	@Test
	public void testQBC() {
		Criteria criteria = session.createCriteria(Employee.class);

		List<Employee> list = criteria.list();
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}

	@After
	public void destroy() {
		session.getTransaction().commit();
		session.close();
	}

}
